<script setup>
import { ref, reactive, computed, onMounted } from "vue";
import { ElMessage } from "element-plus";
import clueApi from "../api/clue";
import request from "../api/request";
import { useAuthStore } from "@/stores/auth";
import { useActivityStore } from "@/stores/activity";
import { processTrackRecords, statusOptions, channelOptions, getLevelColorStyle } from "../utils/clueUtils";

// 搜索条件
const searchParams = reactive({
  name: "",
  phone: "",
  channel: "",
  status: "",
  startDate: "",
  endDate: "",
  clueId: "",
  assignName: "",
});

// 分页相关状态
const currentPage = ref(1);
const pageSize = ref(10);
const totalCount = ref(0);

// 线索列表数据
const clueList = ref([]);
const total = ref(0);
const loading = ref(false);

// 模态框显示状态
const dialogVisible = ref({
  addClue: false,
  followClue: false,
  assignClue: false,
  fakeClue: false,
  confirmTransfer: false,
  clueDetail: false,
});

// 当前操作的线索
const currentClue = ref({});
const clueDetail = ref({ trackRecords: [] });

// 处理后的跟进记录数据
const processedTrackRecords = computed(() => {
  return processTrackRecords(clueDetail.value.trackRecords);
});

// 从公共工具导入的字典数据
// statusOptions - 线索状态选项
// channelOptions - 渠道来源选项

// 获取store实例
const authStore = useAuthStore();
const activityStore = useActivityStore();
// 线索专员列表
const clueSpecialistList = ref([]);
// 活动列表数据
const activityList = ref([]);

// 验证手机号唯一性
const validatePhoneUnique = async (rule, value, callback) => {
  if (!value) {
    callback();
    return;
  }

  try {
    // 实际项目中应该调用验证手机号唯一性的API
    // 暂时模拟验证逻辑
    // const response = await clueApi.checkPhoneUnique(value);

    // 模拟验证通过
    callback();
  } catch (error) {
    callback(new Error("验证失败，请重试"));
  }
};

// 加载线索专员列表
const loadClueSpecialistList = async () => {
  try {
    // 调用用户管理API，获取所有线索专员
    // 根据接口文档，使用GET /users接口
    const response = await request({
      url: "/users",
      method: "GET",
      // 不设置筛选参数，获取所有用户后再在前端筛选角色为线索专员的数据
      // 这样可以避免后端接口可能不支持roleName筛选的问题
    });

    // 处理响应数据，根据接口文档，响应数据在data.rows中
    if (response.data && Array.isArray(response.data.rows)) {
      // 筛选角色为线索专员的数据，并只保留需要的id和name字段
      clueSpecialistList.value = response.data.rows
        .filter((user) => user.roleName === "线索专员")
        .map((user) => ({
          id: user.id,
          name: user.name,
        }));

      // 添加日志以便调试
    } else if (Array.isArray(response.data)) {
      // 兼容直接返回数组的情况
      clueSpecialistList.value = response.data
        .filter((user) => user.roleName === "线索专员")
        .map((user) => ({
          id: user.id,
          name: user.name,
        }));
    } else {
      clueSpecialistList.value = [];
    }
  } catch (error) {
    ElMessage.error("加载线索专员列表失败");
    clueSpecialistList.value = [];
  }
};

// 表单验证规则
const addClueRules = ref({
  phone: [
    { required: true, message: "请输入手机号", trigger: "blur" },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: "请输入11位有效手机号",
      trigger: "blur",
    },
    { validator: validatePhoneUnique, trigger: "blur" },
  ],
  channel: [{ required: true, message: "请选择渠道来源", trigger: "change" }],
  name: [
    { min: 2, max: 20, message: "客户姓名长度应为2-20位", trigger: "blur" },
  ],
  age: [{ type: "number", min: 1, message: "年龄必须大于0", trigger: "blur" }],
  wechat: [
    {
      pattern: /^[a-zA-Z0-9]{1,30}$/,
      message: "微信号只能包含字母和数字，长度30位以内",
      trigger: "blur",
    },
  ],
  qq: [
    {
      pattern: /^\d{1,15}$/,
      message: "QQ号只能包含数字，长度15位以内",
      trigger: "blur",
    },
  ],
});

// 跟进线索表单验证规则
const followClueRules = ref({
  phone: [
    { required: true, message: "请输入手机号", trigger: "blur" },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: "请输入正确的11位手机号码格式",
      trigger: "blur",
    },
  ],
  channel: [{ required: true, message: "请选择渠道来源", trigger: "change" }],
  activityId: [
    { required: false, message: "请选择活动信息", trigger: "change" },
  ],
  name: [
    { required: false, message: "请输入客户姓名", trigger: "blur" },
    { min: 2, max: 20, message: "客户姓名长度应在2-20位之间", trigger: "blur" },
  ],
  gender: [{ required: false, message: "请选择性别", trigger: "change" }],
  age: [
    { required: false, message: "请输入年龄", trigger: "blur" },
    {
      type: "number",
      min: 0,
      max: 100,
      message: "年龄应在0-100之间",
      trigger: "blur",
    },
    { pattern: /^\d+$/, message: "年龄必须为整数数字", trigger: "blur" },
  ],
  wechat: [
    { required: false, message: "请输入微信号", trigger: "blur" },
    {
      pattern: /^[a-zA-Z0-9]{1,30}$/,
      message: "微信号只能包含字母和数字，且不能超过30位",
      trigger: "blur",
    },
    { max: 30, message: "微信号不能超过30位", trigger: "blur" },
  ],
  qq: [
    { required: false, message: "请输入QQ号", trigger: "blur" },
    {
      pattern: /^\d{1,15}$/,
      message: "QQ号只能包含数字，且不能超过15位",
      trigger: "blur",
    },
    { max: 15, message: "QQ号不能超过15位", trigger: "blur" },
  ],
  subject: [{ required: true, message: "请选择意向学科", trigger: "change" }],
  level: [{ required: true, message: "请选择意向等级", trigger: "change" }],
  nextTime: [
    { required: true, message: "请选择下次跟进时间", trigger: "change" },
  ],
  record: [
    { required: true, message: "请输入跟进记录", trigger: "blur" },
    { min: 1, max: 100, message: "跟进记录长度应在1-100之间", trigger: "blur" },
  ],
});

const genderOptions = [
  { label: "男", value: 1 },
  { label: "女", value: 2 },
];

const subjectOptions = [
  { label: "AI智能应用开发(Java)", value: 1 },
  { label: "AI大模型开发(Python)", value: 2 },
  { label: "AI鸿蒙开发", value: 3 },
  { label: "AI大数据", value: 4 },
  { label: "AI嵌入式", value: 5 },
  { label: "AI测试", value: 6 },
  { label: "AI运维", value: 7 },
];

const levelOptions = [
  { label: "近期学习", value: 1 },
  { label: "打算学习(考虑中)", value: 2 },
  { label: "进行了解", value: 3 },
  { label: "打酱油", value: 4 },
];

const falseReasonOptions = [
  { label: "空号", value: 1 },
  { label: "停机", value: 2 },
  { label: "竞品", value: 3 },
  { label: "无法联系", value: 4 },
  { label: "其他", value: 5 },
];

// 模态框表单数据
const addClueForm = ref({
  phone: "",
  channel: null,
  activityId: null,
  name: "",
  gender: null,
  age: null,
  wechat: "",
  qq: "",
});

const followClueForm = ref({
  id: null,
  phone: "",
  channel: null,
  activityId: null,
  name: "",
  gender: null,
  age: null,
  wechat: "",
  qq: null,
  userId: null,
  status: 2,
  subject: null,
  level: null,
  nextTime: "",
  record: "",
});

// 跟进历史数据
const followHistoryList = ref([]);

const assignClueForm = ref({
  userId: null,
});

const fakeClueForm = ref({
  reason: null,
  remark: "",
});

// authStore已在文件顶部声明
// 表单引用
const addClueFormRef = ref(null);
const followClueFormRef = ref(null);

// 分页配置
const pagination = ref({
  currentPage: 1,
  pageSize: 10,
  total: 0,
  onChange: (currentPage) => {
    searchParams.value.page = currentPage;
    loadClueList();
  },
  onSizeChange: (pageSize) => {
    searchParams.value.pageSize = pageSize;
    searchParams.value.page = 1;
    pagination.value.currentPage = 1;
    loadClueList();
  },
});

// 获取线索列表
const loadClueList = async () => {
  loading.value = true;
  try {
    const response = await clueApi.getClueList({
      page: currentPage.value,
      pageSize: pageSize.value,
      clueId: searchParams.clueId,
      phone: searchParams.phone,
      status: searchParams.status,
      channel: searchParams.channel,
      assignName: searchParams.assignName,
    });

    if (response.code === 1) {
      // 获取原始数据
      const rawRows = response.data.rows || [];

      // 规范化数据，确保每个线索都有有效的channel和status字段
      clueList.value = rawRows.map((clue) => {
        // 确保channel和status字段存在并有默认值
        return {
          ...clue,
          // 如果channel不存在或为null/undefined，设置默认值0
          channel: clue.channel ?? 0,
          // 如果status不存在或为null/undefined，设置默认值0
          status: clue.status ?? 0,
          // 特殊处理updateTime，确保它不是对象
          updateTime:
            typeof clue.updateTime === "object"
              ? JSON.stringify(clue.updateTime)
              : clue.updateTime,
        };
      });

      total.value = response.data.total || 0;
      totalCount.value = total.value;
      pagination.value.total = total.value;

      // 调用详细调试函数
      logClueData();
    } else {
      ElMessage.error(response.msg || "获取线索列表失败");
      clueList.value = [];
      total.value = 0;
      totalCount.value = 0;
      pagination.value.total = 0;
    }
  } catch (error) {
    ElMessage.error("获取线索列表失败");
    clueList.value = [];
    total.value = 0;
    totalCount.value = 0;
    pagination.value.total = 0;
  } finally {
    loading.value = false;
  }
};

// 模拟数据已删除

// 处理分页变化
const handleSizeChange = (size) => {
  pageSize.value = size;
  currentPage.value = 1;
  loadClueList();
};

// 组件挂载时初始化活动数据
onMounted(async () => {
  await activityStore.initializeActivities();
});

const handleCurrentChange = (current) => {
  currentPage.value = current;
  loadClueList();
};

// 计算分页数据
const paginatedClueList = computed(() => {
  return clueList.value;
});

// 搜索线索
const search = () => {
  currentPage.value = 1;
  pagination.value.currentPage = 1;
  loadClueList();
};

// 重置搜索条件
const resetSearch = () => {
  Object.keys(searchParams).forEach((key) => {
    searchParams[key] = "";
  });
  currentPage.value = 1;
  pagination.value.currentPage = 1;
  loadClueList();
};

// 根据渠道ID加载活动列表（从store获取）
const loadActivityList = async (channelId = null) => {
  try {
    // 确保活动数据已初始化
    if (!activityStore.initialized) {
      await activityStore.initializeActivities();
    }

    // 从store获取活动数据并根据渠道ID筛选
    if (channelId) {
      activityList.value = activityStore.activities.filter(
        (activity) => activity.channel === channelId
      );
    } else {
      activityList.value = activityStore.activities;
    }
  } catch (error) {
    ElMessage.error("加载活动列表失败");
    // 出错时清空活动列表
    activityList.value = [];
  }
};

// 打开添加线索模态框
const openAddClueDialog = async () => {
  addClueForm.value = {
    phone: "",
    channel: null,
    activityId: null,
    name: "",
    gender: null,
    age: null,
    wechat: "",
    qq: "",
  };

  // 加载活动列表
  await loadActivityList();

  dialogVisible.value.addClue = true;
};

// 添加线索
const addClue = async () => {
  try {
    // 验证表单
    if (!addClueFormRef.value) {
      ElMessage.warning("表单初始化失败");
      return;
    }

    await addClueFormRef.value.validate();

    // 转换数据格式以匹配接口要求
    const formData = {
      ...addClueForm.value,
      gender: addClueForm.value.gender
        ? parseInt(addClueForm.value.gender)
        : null,
      age: addClueForm.value.age ? parseInt(addClueForm.value.age) : null,
      activityId: addClueForm.value.activityId
        ? parseInt(addClueForm.value.activityId)
        : null,
    };
    const response = await clueApi.addClue(formData);
    if (response.code === 1) {
      ElMessage.success("添加成功");
      dialogVisible.value.addClue = false;
      // 重置表单
      if (addClueFormRef.value) {
        addClueFormRef.value.resetFields();
      }
      loadClueList();
    } else {
      ElMessage.error(response.msg || "添加线索失败");
    }
  } catch (error) {
    if (error.name !== "Error") {
      // 表单验证失败的错误不需要额外提示
      return;
    }
    ElMessage.error("添加线索失败");
  }
};

// 打开跟进线索模态框
// 监听渠道变化，动态加载活动列表
const handleChannelChange = async (channelId) => {
  // 确保channelId是数字类型
  if (channelId && typeof channelId === 'string') {
    channelId = parseInt(channelId, 10);
  }
  
  // 先加载活动列表
  if (channelId) {
    await loadActivityList(channelId);
  } else {
    activityList.value = [];
  }
  
  // 在活动列表加载完成后再清空之前选择的活动
  followClueForm.value.activityId = null;
};

// 处理添加线索表单中的渠道变化
const handleAddClueChannelChange = async (channelId) => {
  // 确保channelId是数字类型
  if (channelId && typeof channelId === 'string') {
    channelId = parseInt(channelId, 10);
  }
  
  // 先加载活动列表
  if (channelId) {
    await loadActivityList(channelId);
  } else {
    activityList.value = [];
  }
  
  // 在活动列表加载完成后再清空之前选择的活动
  addClueForm.value.activityId = null;
};

const openFollowClueDialog = async (clue) => {
  currentClue.value = { ...clue };
  
  // 确保clue.channel是数字类型，用于正确加载活动列表
  if (clue.channel && typeof clue.channel === 'string') {
    clue.channel = parseInt(clue.channel, 10);
  }
  
  // 预加载活动数据，确保在显示模态框前数据已就绪
  if (!activityStore.initialized) {
    await activityStore.initializeActivities();
  }

  // 获取线索详情以初始化表单数据和显示跟进历史
  try {
    const response = await clueApi.getClueById(clue.id);
    if (response.code === 1) {
      clueDetail.value = response.data;
      const clueDetailData = response.data;

      // 使用线索详情初始化表单数据
      // 确保channel和activityId是数字类型
      const channel = clueDetailData.channel ? parseInt(clueDetailData.channel, 10) : null;
      const activityId = clueDetailData.activityId ? parseInt(clueDetailData.activityId, 10) : null;
      
      // 先加载活动列表，确保数据已就绪
      if (channel) {
        await loadActivityList(channel);
      } else {
        activityList.value = [];
      }
      
      // 在活动列表加载完成后再设置表单值
      followClueForm.value = {
        id: clueDetailData.id,
        phone: clueDetailData.phone || "",
        channel: channel,
        activityId: activityId,
        name: clueDetailData.name || "",
        gender: clueDetailData.gender || null, // 保持数字类型以正确匹配选项
        age: clueDetailData.age || null,
        wechat: clueDetailData.wechat || "",
        qq: clueDetailData.qq || null,
        userId: clueDetailData.userId || null,
        status: 2, // 跟进中的状态码
        subject: clueDetailData.subject || null, // 保持数字类型以正确匹配选项
        level: clueDetailData.level || null, // 保持数字类型以正确匹配选项
        nextTime: clueDetailData.nextTime || "", // 从数据库加载下次跟进时间
        record: "", // 跟进记录保持为空，等待用户输入
      };
    } else {
      // 如果获取详情失败，使用传入的基本信息初始化
      // 确保channel和activityId是数字类型
      const failChannel = clue.channel ? parseInt(clue.channel, 10) : null;
      const failActivityId = clue.activityId ? parseInt(clue.activityId, 10) : null;
      
      // 先加载活动列表，确保数据已就绪
      if (failChannel) {
        await loadActivityList(failChannel);
      } else {
        activityList.value = [];
      }
      
      // 在活动列表加载完成后再设置表单值
      followClueForm.value = {
        id: clue.id,
        phone: clue.phone || "",
        channel: failChannel,
        activityId: failActivityId,
        name: clue.name || "",
        gender: clue.gender || null, // 保持数字类型以正确匹配选项
        age: clue.age || null,
        wechat: clue.wechat || "",
        qq: clue.qq || null,
        userId: clue.userId || null,
        status: 2,
        subject: clue.subject || null, // 保持数字类型以正确匹配选项
        level: clue.level || null, // 保持数字类型以正确匹配选项
        nextTime: "",
        record: "",
      };
    }
  } catch (error) {
    // 错误情况下的兜底初始化
    // 确保channel和activityId是数字类型
    const errorChannel = clue.channel ? parseInt(clue.channel, 10) : null;
    const errorActivityId = clue.activityId ? parseInt(clue.activityId, 10) : null;
    
    // 先加载活动列表，确保数据已就绪
    if (errorChannel) {
      await loadActivityList(errorChannel);
    } else {
      activityList.value = [];
    }
    
    // 在活动列表加载完成后再设置表单值
    followClueForm.value = {
      id: clue.id,
      phone: clue.phone || "",
      channel: errorChannel,
      activityId: errorActivityId,
      name: clue.name || "",
      gender: clue.gender || null, // 保持数字类型以正确匹配选项
      age: clue.age || null,
      wechat: clue.wechat || "",
      qq: clue.qq || null,
      userId: clue.userId || null,
      status: 2,
      subject: clue.subject || null, // 保持数字类型以正确匹配选项
      level: clue.level || null, // 保持数字类型以正确匹配选项
      nextTime: "",
      record: "",
    };
  }

  // 延迟打开模态框，确保所有异步操作完成
  setTimeout(() => {
    dialogVisible.value.followClue = true;
  }, 10);
};

// 跟进线索
const followClue = async () => {
  try {
    // 表单验证
    const valid = await followClueFormRef.value.validate();
    if (!valid) {
      return;
    }

    // 转换数据格式以匹配接口要求
    // 由于el-date-picker已经设置了value-format="yyyy-MM-ddTHH:mm:ss"，
    // 我们直接使用这个值，不再进行额外的格式化处理
    // 确保nextTime以YYYY-MM-DDTHH:mm:ss格式发送
    let formattedNextTime = null;
    if (followClueForm.value.nextTime) {
      const date = new Date(followClueForm.value.nextTime);
      if (!isNaN(date.getTime())) {
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, "0");
        const day = String(date.getDate()).padStart(2, "0");
        const hours = String(date.getHours()).padStart(2, "0");
        const minutes = String(date.getMinutes()).padStart(2, "0");
        const seconds = String(date.getSeconds()).padStart(2, "0");
        formattedNextTime = `${year}-${month}-${day}T${hours}:${minutes}:${seconds}`;
      }
    }
    
    const formData = {
      ...followClueForm.value,
      subject: followClueForm.value.subject
        ? parseInt(followClueForm.value.subject)
        : null,
      level: followClueForm.value.level
        ? parseInt(followClueForm.value.level)
        : null,
      gender: followClueForm.value.gender
        ? parseInt(followClueForm.value.gender)
        : null,
      age: followClueForm.value.age ? parseInt(followClueForm.value.age) : null,
      channel: followClueForm.value.channel
        ? parseInt(followClueForm.value.channel)
        : null,
      nextTime: formattedNextTime,
    };
    const response = await clueApi.followClue(formData);
    if (response.code === 1) {
      ElMessage.success("跟进成功");
      dialogVisible.value.followClue = false;
      loadClueList();
    } else {
      ElMessage.error(response.msg || "跟进线索失败");
    }
  } catch (error) {
    ElMessage.error("跟进线索失败");
  }
};

// 打开分配线索模态框
const openAssignClueDialog = async (clue) => {
  currentClue.value = { ...clue };
  assignClueForm.value = { userId: null };

  // 加载线索专员列表
  await loadClueSpecialistList();

  dialogVisible.value.assignClue = true;
};

// 分配线索
const assignClue = async () => {
  if (!assignClueForm.value.userId) {
    ElMessage.warning("请选择分配人");
    return;
  }

  try {
    const response = await clueApi.assignClue(
      currentClue.value.id,
      assignClueForm.value.userId
    );
    if (response.code === 1) {
      ElMessage.success("分配成功");
      dialogVisible.value.assignClue = false;
      loadClueList();
    } else {
      ElMessage.error(response.msg || "分配失败");
    }
  } catch (error) {
    ElMessage.error("分配线索失败");
  }
};

// 打开伪线索模态框
const openFakeClueDialog = (clue) => {
  currentClue.value = { ...clue };
  fakeClueForm.value = { reason: null, remark: "" };
  dialogVisible.value.fakeClue = true;
};

// 标记伪线索
const markAsFakeClue = async () => {
  if (!fakeClueForm.value.reason) {
    ElMessage.warning("请选择伪线索原因");
    return;
  }

  try {
    // 转换数据格式以匹配接口要求
    const formData = {
      ...fakeClueForm.value,
      reason: fakeClueForm.value.reason
        ? parseInt(fakeClueForm.value.reason)
        : null,
    };
    const response = await clueApi.markAsFakeClue(
      currentClue.value.id,
      formData
    );
    if (response.code === 1) {
      ElMessage.success("处理成功");
      dialogVisible.value.fakeClue = false;
      loadClueList();
    } else {
      ElMessage.error(response.msg || "处理失败");
    }
  } catch (error) {
    ElMessage.error("标记伪线索失败");
  }
};

// 打开转商机确认模态框
const openTransferToBusinessDialog = (clue) => {
  currentClue.value = { ...clue };
  dialogVisible.value.confirmTransfer = true;
};

// 转商机处理
const transferToBusiness = async () => {
  try {
    const response = await clueApi.transferToBusiness(currentClue.value.id);
    if (response.code === 1) {
      ElMessage.success("转商机成功");
      dialogVisible.value.confirmTransfer = false;
      loadClueList();
    } else {
      ElMessage.error(response.msg || "转商机失败");
    }
  } catch (error) {
    ElMessage.error("转商机失败");
  }
};

// 查看线索详情
const viewClueDetail = async (id) => {
  try {
    const response = await clueApi.getClueById(id);
    if (response.code === 1) {
      clueDetail.value = response.data;
      dialogVisible.value.clueDetail = true;
    } else {
      ElMessage.error(response.msg || "获取线索详情失败");
    }
  } catch (error) {
    ElMessage.error("获取线索详情失败");
  }
};

// 格式化性别
const formatGender = (gender) => {
  const genderMap = { 1: "男", 2: "女" };
  return genderMap[gender] || "-";
};

// 格式化渠道
const formatChannel = (channel) => {
  if (!channel && channel !== 0) return "-";
  return activityStore.getChannelNameById(Number(channel)) || "-";
};

// 格式化活动名称
const formatActivityName = (activityId) => {
  if (!activityId && activityId !== 0) return "-";
  return activityStore.getActivityNameById(Number(activityId)) || "-";
};

// 格式化状态
const formatStatus = (status) => {
  if (!status && status !== 0) return "-";
  // 直接使用数字映射，同时处理字符串和数字类型
  switch (Number(status)) {
    case 1:
      return "待分配";
    case 2:
      return "待跟进";
    case 3:
      return "跟进中";
    case 4:
      return "伪线索";
    case 5:
      return "转为商机";
    default:
      return "-";
  }
};

// getLevelColorStyle已从公共工具导入

// 格式化意向等级
const formatLevel = (level) => {
  // 根据数据库表设计的正确映射关系
  const levelMap = {
    1: "近期学习",
    2: "打算学习(考虑中)",
    3: "进行了解",
    4: "打酱油"
  };
  // 如果是字符串且包含特定文本，直接返回对应的值
  if (typeof level === "string") {
    if (level.includes("近期学习")) return "近期学习";
    if (level.includes("打算学习") || level.includes("考虑中"))
      return "打算学习(考虑中)";
    if (level.includes("进行了解")) return "进行了解";
    if (level.includes("打酱油")) return "打酱油";
  }
  return levelMap[level] || level || "-";
};

// 格式化学科
const formatSubject = (subject) => {
  // 扩展学科映射，确保包含所有可能的值
  const subjectMap = {
    1: "Java",
    2: "Python",
    3: "前端",
    4: "大数据",
    5: "人工智能",
    6: "AI鸿蒙开发",
    7: "AI测试",
    8: "AI运维",
    9: "AI智能应用开发(Java)",
    1: "Java",
    2: "Python",
    3: "前端",
    4: "大数据",
    5: "人工智能",
    6: "AI鸿蒙开发",
    7: "AI测试",
    8: "AI运维",
    9: "AI智能应用开发(Java)",
  };
  // 如果是字符串且已经是可读名称，直接返回
  if (typeof subject === "string" && subject.length > 0) {
    return subject;
  }
  return subjectMap[subject] || subject || "-";
};

// 格式化日期时间
const formatDateTime = (dateValue) => {
  if (!dateValue) return "-";

  try {
    // 处理日期字符串
    if (typeof dateValue === "string") {
      // 如果已经是格式化的字符串，直接返回
      if (/\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}/.test(dateValue)) {
        return dateValue;
      }
      // 处理ISO格式或其他格式的日期字符串
      const date = new Date(dateValue);
      if (!isNaN(date.getTime())) {
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, "0");
        const day = String(date.getDate()).padStart(2, "0");
        const hours = String(date.getHours()).padStart(2, "0");
        const minutes = String(date.getMinutes()).padStart(2, "0");
        const seconds = String(date.getSeconds()).padStart(2, "0");
        return `${year}-${month}-${day}T${hours}:${minutes}:${seconds}`;
      }
    }
    // 处理日期对象
    else if (dateValue instanceof Date && !isNaN(dateValue.getTime())) {
      const year = dateValue.getFullYear();
      const month = String(dateValue.getMonth() + 1).padStart(2, "0");
      const day = String(dateValue.getDate()).padStart(2, "0");
      const hours = String(dateValue.getHours()).padStart(2, "0");
      const minutes = String(dateValue.getMinutes()).padStart(2, "0");
      const seconds = String(dateValue.getSeconds()).padStart(2, "0");
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    }

    // 返回原始值的字符串表示
    return String(dateValue);
  } catch (e) {
    return String(dateValue || "-");
  }
};

// 格式化伪线索原因
const formatFalseReason = (reason) => {
  const reasonMap = {
    1: "空号/停机",
    2: "无需课程",
    3: "重复线索",
    4: "错误号码",
    5: "其他原因",
  };
  return reasonMap[reason] || "-";
};

// 格式化跟进类型
const formatTrackType = (type) => {
  const typeMap = { 1: "电话", 2: "微信", 3: "邮件", 4: "其他" };
  return typeMap[type] || "-";
};

// 格式化日期
const formatDate = (dateValue) => {
  if (!dateValue) return "-";
  // 处理对象类型的日期
  if (typeof dateValue === "object") {
    try {
      // 尝试提取日期字符串或使用对象的toString方法
      if (dateValue.toString) {
        return dateValue.toString();
      }
      return JSON.stringify(dateValue);
    } catch (e) {
      return "-";
    }
  }
  return String(dateValue);
};

// 添加更详细的调试函数
const logClueData = () => {
  if (clueList.value.length > 0) {
    const firstClue = clueList.value[0];



  }
};

// 初始加载
onMounted(async () => {
  // 确保活动数据已初始化
  if (!activityStore.initialized) {
    await activityStore.initializeActivities();
  }
  loadClueList();
});
</script>

<template>
  <div class="clue-view">
    <div class="page-header">
      <h2>线索管理</h2>
    </div>

    <!-- 搜索条件区域 -->
    <div class="search-container">
      <el-form :inline="true" size="small">
        <el-form-item label="线索ID:">
          <el-input
            v-model="searchParams.clueId"
            placeholder="请输入"
          ></el-input>
        </el-form-item>
        <el-form-item label="手机号:">
          <el-input
            v-model="searchParams.phone"
            placeholder="请输入"
          ></el-input>
        </el-form-item>
        <el-form-item label="线索状态:">
          <el-select v-model="searchParams.status" placeholder="请选择">
            <el-option label="待分配" value="1"></el-option>
            <el-option label="待跟进" value="2"></el-option>
            <el-option label="跟进中" value="3"></el-option>
            <el-option label="伪线索" value="4"></el-option>
            <el-option label="转为商机" value="5"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="线索来源:">
          <el-select v-model="searchParams.channel" placeholder="请选择">
            <el-option label="线上活动" value="1"></el-option>
            <el-option label="推广介绍" value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="线索归属:">
          <el-input
            v-model="searchParams.assignName"
            placeholder="请输入归属人姓名"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="search">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 操作按钮区域 -->
    <div class="action-container">
      <el-button type="primary" @click="openAddClueDialog"
        >+ 新建线索</el-button
      >
    </div>

    <!-- 使用预设样式类来确保滚动条和分页正确显示 -->
    <div class="content-wrapper">
      <!-- 表格内容容器 -->
      <div class="table-wrapper">
        <el-table :data="clueList" stripe :loading="loading">
          <el-table-column
            prop="id"
            label="线索ID"
            width="100"
          ></el-table-column>
          <el-table-column
            prop="phone"
            label="手机号"
            width="120"
          ></el-table-column>
          <el-table-column
            prop="name"
            label="客户姓名"
            width="100"
          ></el-table-column>
          <el-table-column prop="channel" label="渠道来源" width="100">
            <template #default="{ row }">
              {{ row.channel ? formatChannel(row.channel) : "-" }}
            </template>
          </el-table-column>
          <el-table-column prop="status" label="线索状态" width="100">
            <template #default="{ row }">
              {{ row.status ? formatStatus(row.status) : "-" }}
            </template>
          </el-table-column>
          <el-table-column
            prop="assignName"
            label="归属人"
            width="100"
          ></el-table-column>
          <el-table-column
            prop="createTime"
            label="创建时间"
            width="150"
          ></el-table-column>
          <el-table-column prop="nextTime" label="下一次跟进时间" width="150">
            <template #default="{ row }">
              {{ row.nextTime ? formatDate(row.nextTime) : "-" }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200" fixed="right">
            <template #default="{ row }">
              <!-- 1. 分配按钮：只有管理员可以分配线索，且只在待分配状态显示 -->
              <template
                v-if="row.status === 1 && authStore.roleLabel === 'admin'"
              >
                <el-button type="text" @click="openAssignClueDialog(row)"
                  >分配</el-button
                >
              </template>

              <!-- 2. 跟进按钮：只有线索归属人可以跟进，且只在待跟进、跟进中状态显示 -->
              <template
                v-if="
                  (row.status === 2 || row.status === 3) &&
                  row.userId === authStore.userId
                "
              >
                <el-button type="text" @click="openFollowClueDialog(row)"
                  >跟进</el-button
                >
              </template>

              <!-- 3. 伪线索按钮：只有线索归属人可以标记，且只在待跟进、跟进中状态显示 -->
              <template
                v-if="
                  (row.status === 2 || row.status === 3) &&
                  row.userId === authStore.userId
                "
              >
                <el-button type="text" @click="openFakeClueDialog(row)"
                  >伪线索</el-button
                >
              </template>

              <!-- 4. 转商机按钮：只有线索归属人可以转商机，且只在待跟进、跟进中状态显示 -->
              <template
                v-if="
                  (row.status === 2 || row.status === 3) &&
                  row.userId === authStore.userId
                "
              >
                <el-button
                  type="text"
                  @click="openTransferToBusinessDialog(row)"
                  >转商机</el-button
                >
              </template>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页容器 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          layout="total, prev, pager, next, sizes, jumper"
          :total="totalCount"
          :page-sizes="[10, 20, 50, 100]"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          background
        />
      </div>
    </div>

    <!-- 新增线索模态框 -->
    <el-dialog
      v-model="dialogVisible.addClue"
      title="添加线索"
      width="500px"
      center
    >
      <el-form
        ref="addClueFormRef"
        :model="addClueForm"
        :rules="addClueRules"
        label-width="100px"
      >
        <el-form-item label="* 手机号:" prop="phone" required>
          <el-input
            v-model="addClueForm.phone"
            placeholder="请输入11位手机号"
            maxlength="11"
          ></el-input>
        </el-form-item>
        <el-form-item label="* 渠道来源:" prop="channel" required>
          <el-select 
            v-model="addClueForm.channel" 
            placeholder="请选择渠道来源"
            @change="handleAddClueChannelChange"
          >
            <el-option
              v-for="option in channelOptions"
              :key="option.value"
              :label="option.label"
              :value="option.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="活动信息:" prop="activityId">
          <el-select
            v-model="addClueForm.activityId"
            placeholder="请选择活动（选填）"
            :disabled="!addClueForm.channel"
          >
            <el-option
              v-for="option in activityList"
              :key="option.id"
              :label="option.name"
              :value="option.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="客户姓名:" prop="name">
          <el-input
            v-model="addClueForm.name"
            placeholder="请输入客户姓名（2-20位）"
            maxlength="20"
          ></el-input>
        </el-form-item>
        <el-form-item label="性别:">
          <el-select v-model="addClueForm.gender" placeholder="请选择">
            <el-option label="男" value="1"></el-option>
            <el-option label="女" value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="年龄:" prop="age">
          <el-input
            v-model.number="addClueForm.age"
            placeholder="请输入年龄（大于0）"
            type="number"
          ></el-input>
        </el-form-item>
        <el-form-item label="微信号:" prop="wechat">
          <el-input
            v-model="addClueForm.wechat"
            placeholder="请输入微信号（字母+数字，30位以内）"
            maxlength="30"
          ></el-input>
        </el-form-item>
        <el-form-item label="QQ:" prop="qq">
          <el-input
            v-model="addClueForm.qq"
            placeholder="请输入QQ号（数字，15位以内）"
            maxlength="15"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible.addClue = false">取消</el-button>
        <el-button type="primary" @click="addClue">确定</el-button>
      </template>
    </el-dialog>

    <!-- 跟进线索模态框 -->
    <el-dialog
      v-model="dialogVisible.followClue"
      :title="`跟进线索(线索ID:${currentClue?.id || '-'})`"
      width="600px"
      center
    >
      <el-form
        :model="followClueForm"
        :rules="followClueRules"
        ref="followClueFormRef"
        label-width="100px"
      >
        <div class="form-row">
          <el-form-item label="* 手机号:" required prop="phone">
            <el-input
              v-model="followClueForm.phone"
              placeholder="请输入手机号"
              disabled
            ></el-input>
          </el-form-item>
          <el-form-item label="* 渠道来源:" required prop="channel">
            <el-select
              v-model="followClueForm.channel"
              placeholder="请选择渠道来源"
              disabled
              @change="handleChannelChange"
            >
              <el-option
                v-for="option in channelOptions"
                :key="option.value"
                :label="option.label"
                :value="option.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </div>
        <div class="form-row">
          <el-form-item label="活动信息:" prop="activityId">
            <el-select
              v-model="followClueForm.activityId"
              placeholder="请选择活动"
              :disabled="!followClueForm.channel"
            >
              <el-option
                v-for="option in activityList"
                :key="option.id"
                :label="option.name"
                :value="option.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="客户姓名:" prop="name">
            <el-input
              v-model="followClueForm.name"
              placeholder="请输入客户姓名"
            ></el-input>
          </el-form-item>
        </div>
        <div class="form-row">
          <el-form-item label="性别:" prop="gender">
            <el-select v-model="followClueForm.gender" placeholder="请选择">
              <el-option label="男" :value="1"></el-option>
              <el-option label="女" :value="2"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="年龄:" prop="age">
            <el-input
              v-model.number="followClueForm.age"
              placeholder="请输入年龄"
              type="number"
            ></el-input>
          </el-form-item>
        </div>
        <div class="form-row">
          <el-form-item label="微信号:" prop="wechat">
            <el-input
              v-model="followClueForm.wechat"
              placeholder="请输入微信号"
            ></el-input>
          </el-form-item>
          <el-form-item label="QQ:" prop="qq">
            <el-input
              v-model="followClueForm.qq"
              placeholder="请输入QQ号"
            ></el-input>
          </el-form-item>
        </div>
        <div class="form-row">
          <el-form-item label="* 意向学科:" required prop="subject">
            <el-select
              v-model="followClueForm.subject"
              placeholder="请选择意向学科"
            >
              <el-option label="Java" :value="1"></el-option>
              <el-option label="Python" :value="2"></el-option>
              <el-option label="前端" :value="3"></el-option>
              <el-option label="大数据" :value="4"></el-option>
              <el-option label="人工智能" :value="5"></el-option>
              <el-option label="AI鸿蒙开发" :value="6"></el-option>
              <el-option label="AI测试" :value="7"></el-option>
              <el-option label="AI运维" :value="8"></el-option>
              <el-option label="AI应用开发(Java)" :value="9"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="* 意向等级:" required prop="level">
            <el-select
              v-model="followClueForm.level"
              placeholder="请选择意向等级"
            >
              <el-option
                v-for="option in levelOptions"
                :key="option.value"
                :label="option.label"
                :value="option.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </div>
        <el-form-item label="* 下次跟进:" required prop="nextTime">
          <el-date-picker
            v-model="followClueForm.nextTime"
            type="datetime"
            placeholder="选择日期时间"
            style="width: 100%"
            value-format="YYYY-MM-DDTHH:mm:ss"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="* 跟进记录:" required prop="record">
          <el-input
            v-model="followClueForm.record"
            type="textarea"
            placeholder="请输入跟进记录"
            rows="3"
            maxlength="100"
            show-word-limit
          ></el-input>
        </el-form-item>
      </el-form>

      <!-- 跟进历史 -->
      <div class="follow-history">
        <h4 style="margin: 20px 0 10px 0">跟进历史</h4>
        <el-table :data="processedTrackRecords" stripe size="small">
          <el-table-column label="意向等级" width="120">
            <template #default="scope">
              <span :style="getLevelColorStyle(scope.row.level || '')">
                {{ formatLevel(scope.row.level || "") }}
              </span>
            </template>
          </el-table-column>
          <el-table-column label="意向学科" width="150">
            <template #default="scope">
              {{ formatSubject(scope.row.subject || "") }}
            </template>
          </el-table-column>
          <el-table-column label="跟进人" width="100">
            <template #default="scope">
              {{ scope.row.assignName || "-" }}
            </template>
          </el-table-column>
          <el-table-column label="跟进时间" width="160">
            <template #default="scope">
              {{ formatDateTime(scope.row.createTime || "") }}
            </template>
          </el-table-column>
          <el-table-column label="下次跟进时间" width="160">
            <template #default="scope">
              {{ formatDateTime(scope.row.nextTime || "") }}
            </template>
          </el-table-column>
          <el-table-column label="跟进记录">
            <template #default="scope">
              {{ scope.row.record || "-" }}
            </template>
          </el-table-column>
        </el-table>
      </div>

      <template #footer>
        <el-button @click="dialogVisible.followClue = false">取消</el-button>
        <el-button type="primary" @click="followClue">确定</el-button>
      </template>
    </el-dialog>

    <!-- 分配线索模态框 -->
    <el-dialog
      v-model="dialogVisible.assignClue"
      title="分配线索"
      width="400px"
      center
    >
      <el-form label-width="100px">
        <el-form-item label="* 请选择人员:" required>
          <el-select
            v-model="assignClueForm.userId"
            placeholder="请选择"
            required
          >
            <el-option
              v-for="specialist in clueSpecialistList"
              :key="specialist.id"
              :label="specialist.name"
              :value="specialist.id"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible.assignClue = false">取消</el-button>
        <el-button type="primary" @click="assignClue">确定</el-button>
      </template>
    </el-dialog>

    <!-- 伪线索上报模态框 -->
    <el-dialog
      v-model="dialogVisible.fakeClue"
      title="伪线索上报"
      width="400px"
      center
    >
      <el-form label-width="100px">
        <el-form-item label="* 原因:" required>
          <el-select v-model="fakeClueForm.reason" placeholder="请选择原因">
            <el-option label="空号/停机" value="1"></el-option>
            <el-option label="无需课程" value="2"></el-option>
            <el-option label="重复线索" value="3"></el-option>
            <el-option label="错误号码" value="4"></el-option>
            <el-option label="其他原因" value="5"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注:">
          <el-input
            v-model="fakeClueForm.remark"
            type="textarea"
            placeholder="请输入备注说明"
            rows="3"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible.fakeClue = false">取消</el-button>
        <el-button type="primary" @click="markAsFakeClue">确定</el-button>
      </template>
    </el-dialog>

    <!-- 转商机确认模态框 -->
    <el-dialog
      v-model="dialogVisible.confirmTransfer"
      title="提示"
      width="300px"
      center
    >
      <div style="text-align: center; padding: 20px 0">确认转为商机？</div>
      <template #footer>
        <el-button @click="dialogVisible.confirmTransfer = false"
          >取消</el-button
        >
        <el-button type="primary" @click="transferToBusiness">确定</el-button>
      </template>
    </el-dialog>

    <!-- 线索详情模态框 -->
    <el-dialog
      v-model="dialogVisible.clueDetail"
      title="线索详情"
      width="700px"
      center
    >
      <el-form label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="线索ID:">
              <el-input v-model="clueDetail.id" disabled></el-input>
            </el-form-item>
            <el-form-item label="手机号:">
              <el-input v-model="clueDetail.phone" disabled></el-input>
            </el-form-item>
            <el-form-item label="客户姓名:">
              <el-input v-model="clueDetail.name" disabled></el-input>
            </el-form-item>
            <el-form-item label="渠道来源:">
              <el-input
                :value="formatChannel(clueDetail.channel)"
                disabled
              ></el-input>
            </el-form-item>
            <el-form-item label="活动信息:">
              <el-input
                :value="formatActivityName(clueDetail.activityId)"
                disabled
              ></el-input>
            </el-form-item>
            <el-form-item label="性别:">
              <el-input
                :value="formatGender(clueDetail.gender)"
                disabled
              ></el-input>
            </el-form-item>
            <el-form-item label="年龄:">
              <el-input v-model="clueDetail.age" disabled></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="微信号:">
              <el-input v-model="clueDetail.wechat" disabled></el-input>
            </el-form-item>
            <el-form-item label="QQ:">
              <el-input v-model="clueDetail.qq" disabled></el-input>
            </el-form-item>
            <el-form-item label="归属人:">
              <el-input v-model="clueDetail.assignName" disabled></el-input>
            </el-form-item>
            <el-form-item label="线索状态:">
              <el-input
                :value="formatStatus(clueDetail.status)"
                disabled
              ></el-input>
            </el-form-item>
            <el-form-item label="意向学科:">
              <el-input
                :value="formatSubject(clueDetail.subject)"
                disabled
              ></el-input>
            </el-form-item>
            <el-form-item label="意向等级:">
              <el-input
                :value="formatLevel(clueDetail.level)"
                disabled
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="下次跟进时间:">
          <el-input v-model="clueDetail.nextTime" disabled></el-input>
        </el-form-item>
        <el-form-item label="创建时间:">
          <el-input v-model="clueDetail.createTime" disabled></el-input>
        </el-form-item>
        <el-form-item label="更新时间:">
          <el-input v-model="clueDetail.updateTime" disabled></el-input>
        </el-form-item>
      </el-form>

      <!-- 跟进历史 -->
      <div class="follow-history">
        <h4 style="margin: 20px 0 10px 0">跟进历史</h4>
        <el-table :data="clueDetail.trackRecords" stripe size="small">
          <el-table-column
            prop="level"
            label="意向等级"
            width="100"
            :formatter="formatLevel"
          ></el-table-column>
          <el-table-column
            prop="subject"
            label="意向学科"
            width="120"
            :formatter="formatSubject"
          ></el-table-column>
          <el-table-column
            prop="assignName"
            label="跟进人"
            width="80"
          ></el-table-column>
          <el-table-column prop="record" label="跟进记录"></el-table-column>
          <el-table-column
            prop="createTime"
            label="跟进时间"
            width="150"
          ></el-table-column>
        </el-table>
      </div>

      <template #footer>
        <el-button @click="dialogVisible.clueDetail = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.clue-view {
  background-color: #fff;
  min-height: 100%;
  padding: 20px;
}
.form-row {
  display: flex;
  gap: 20px;
}
.form-row .el-form-item {
  flex: 1;
  margin-bottom: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  font-size: 20px;
  color: #303133;
}

/* 搜索条件区域 */
.search-container {
  background-color: #fff;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 10px 20px;
  margin-bottom: 15px;
  display: flex;
  align-items: center;
}

/* 确保表单内所有元素在一行 */
:deep(.el-form--inline) {
  display: flex;
  align-items: center;
  flex-wrap: nowrap;
  width: 100%;
}

.demo-pagination-block + .demo-pagination-block {
  margin-top: 10px;
}

.demo-pagination-block .demonstration {
  margin-bottom: 16px;
}

:deep(.el-form--inline .el-form-item) {
  margin-right: 15px;
  margin-bottom: 0;
}

/* 按钮样式调整 */
:deep(.el-form--inline .el-form-item:last-child) {
  margin-left: auto;
  margin-right: 0;
}

/* 调整输入框和选择器的宽度 */
:deep(.el-input__wrapper) {
  min-width: 160px;
}

:deep(.el-select) {
  min-width: 160px;
}

/* 操作按钮区域 */
.action-container {
  margin-bottom: 20px;
}

/* 内容整体容器 */
.content-wrapper {
  background-color: #fff;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  overflow: hidden;
  position: relative;
}

/* 表格内容容器 */
.table-wrapper {
  overflow-x: auto; /* 允许水平滚动 */
  overflow-y: auto; /* 允许垂直滚动 */
  height: 400px; /* 固定高度确保滚动条出现 */
  border-bottom: 1px solid #ebeef5;
}

/* 分页容器 */
.pagination-wrapper {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  padding: 15px 20px;
  background-color: #fff;
  clear: both;
  position: relative;
  z-index: 10;
  box-sizing: border-box;
  width: 100%;
}

/* 调整表格样式 */
:deep(.el-table) {
  border-top: none;
}

:deep(.el-table th) {
  background-color: #f5f7fa;
  font-weight: 500;
  color: #606266;
}

:deep(.el-table td) {
  border-bottom: 1px solid #ebeef5;
}

/* 操作按钮间距 */
:deep(.el-table .el-button) {
  margin-right: 10px;
}

/* 响应式布局 */
@media screen and (max-width: 768px) {
  .clue-view {
    padding: 10px;
  }

  .search-container {
    padding: 15px;
  }

  .el-form--inline .el-form-item {
    margin-right: 0;
    margin-bottom: 15px;
  }
}
</style>
